#!/usr/bin/env perl
use warnings;
use strict;

use DBI;
use CGI;
use Digest::SHA;

# change /path/to/includes to match your setup
BEGIN {
    use constant INCLUDES => '/path/to/includes';
    require(INCLUDES . '/functions.pl');
    require(INCLUDES . '/database.pl');
    require(INCLUDES . '/images.pl');
}

# create database connection
my $dbh = DBI->connect(DB_DBI, DB_USER, DB_PASS);

# get cookie data (login credentials)
my $cgi = CGI->new;
my $c_user = $cgi->cookie('user');

# fetch user credentials
my %user = get_user($dbh, $c_user);

# check user credentials
if (not defined($user{'hash'})) {
    $dbh->disconnect;
    error BAD_CREDS;
} elsif (not ($user{'permissions'} & ACCESS_IMG)) {
    $dbh->disconnect;
    error ACCESS_DENIED;
}

# get page count info
my ($page, $page_max) = get_page_info($dbh, $cgi);

# should nws images be displayed? default 'no'
my $f_nws = '';
$f_nws = $cgi->param('nws') if (defined($cgi->param('nws')));
my $view_nws = ($f_nws eq 'true') ? 1 : 0;

# generate secret hash
my $sha2obj = Digest::SHA->new(512);
$sha2obj->add(SECRET);
my $secret_hash = $sha2obj->hex_digest();

# generate encrypted secret
my $cipher = Crypt::CBC->new(
    -key    => $secret_hash,
    -cipher => "Rijndael"
);

my $nonce = int(rand(65535));
my $ptext = # TODO
my $ctext = $cipher->encrypt
$sha2obj->add(string_zip($user{'hash'}, $seed_hash));
my $secret_hash = $sha2obj->hex_digest();

# display page content
html_begin;
html_title 'Images';
html_css(('images.css'));
html_body;

print_upload_form($user{'hash'}, $secret_hash) if ($user{'permissions'} & ACCESS_IMG_UP);
print_nav($page, $page_max, $view_nws);
print_images($dbh, $page, $view_nws, $user{'permissions'} & ACCESS_IMG_UP);
print_nav($page, $page_max, $view_nws);
print_stats($dbh, $cgi);

html_end;

$dbh->disconnect;
